package com.thrc.borrow.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.thrc.borrow.entity.User;
import com.thrc.borrow.pay.WeixinPayConstants;
import com.thrc.borrow.pay.util.Log;
import com.thrc.borrow.service.UserService;
import com.thrc.borrow.utils.WeichatRequestUtil;
import com.thrc.borrow.vo.UserVo;

@RequestMapping("/wechat")
@Controller
public class WechatController {

	@Autowired
	private UserService userService;

	// 课程列表
	public static String uri = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx44e7c3330b3a4720&redirect_uri=http%3A%2F%2Fwww.wuhanquan.com%2Fweixin%2Fcourse_list.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

	// 我的课程
	public static String uri2 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx44e7c3330b3a4720&redirect_uri=http%3A%2F%2Fwww.wuhanquan.com%2Fwechat%2Fpath%2Fcontrol%3Fmid%3D1&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

	// 路由控制
	@RequestMapping(value = "/path/control", method = RequestMethod.GET)
	public String pathController(HttpServletRequest req, HttpServletResponse resp, 
			                    @RequestParam("mid") int mid,
								@RequestParam("code") String code)
			throws Exception {

		String appid = WeixinPayConstants.appid;
		String secret = WeixinPayConstants.appsecret;
		// 拿到code
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + "appid=" + appid + "&" + "secret=" + secret
				+ "&" + "code=" + code + "&" + "grant_type=authorization_code";

		// code换取access_token
		String tokenStr = WeichatRequestUtil.SendGET(url);
		JSONObject obj = JSON.parseObject(tokenStr);

		String token = obj.getString("access_token");
		String openid = obj.getString("openid");
		User t = new User();
		t.setOpenid(openid);

		List<UserVo> userList = userService.selectAll(t);
		if (userList.size() == 0) {
			userService.insert(t);
		}
		if(mid==1){
			resp.sendRedirect("http://www.wuhanquan.com/weixin/course_list.html#"+openid);
		}else{
			resp.sendRedirect("http://www.wuhanquan.com/weixin/my_course.html#"+openid);
		}

		return null;
	}

}
